<?php

class AuthenticationController extends Zend_Controller_Action {

    private function _setTitle($name) {
      $view = Zend_Layout::getMvcInstance()->getView(); 
      $this->view->title = $view->translate->_($name);
      $this->view->headTitle($this->view->title);
   }
    
    public function init() {
      $this->_helper->layout->setLayout('default');
      $_name = str_replace('Action', '', $this->getRequest()->getActionName());
      $this->_setTitle(ucfirst($_name));
   }

    public function indexAction() {
    }

    public function loginAction() {
       if(Zend_Auth::getInstance()->hasIdentity()) {
          //    		$this->_redirect('index/index');
          //			pr(Zend_Auth::getInstance()->getIdentity());
       }

       $form = new Form_Login();
       if($this->getRequest()->isPost()) {
          if($form->isValid($this->_request->getPost())) {             
             $authAdapter = $this->getAuthAdapter();
             $username = $form->getValue('username');
             $password = $form->getValue('password');
             $authAdapter->setIdentity($username)
                         ->setCredential($password);
             
             //pr($authAdapter);
             $result = null;
             $result = Zend_Auth::getInstance()->authenticate($authAdapter);
             
             $messages = $result->getMessages();
             $msg = implode("<br />\n", $messages);

             if($result->isValid()) {
                Zend_Auth::getInstance()->clearIdentity();
                Zend_Auth::getInstance()->getStorage()->write($authAdapter->getResultRowObject()->id);
                
                $defaultNamespace = new Zend_Session_Namespace('Default');
                $defaultNamespace->username = $username;
                $this->_redirect("index/index");
                
                /*$auth->getStorage()->write($adapter->getResultRowObject()->id);
                if(!empty($_SERVER['HTTP_REFERER'])) {
                  header('Location: '.$_SERVER['HTTP_REFERER']);
                } else {
                  $this->_redirect('/');
                }*/
                
             } else {
                $this->view->errorMessage = $msg;
             }
          }
       }


       $this->view->form = $form;


    }
    
    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        Zend_Registry::set('role', 'guests');
        $user = new Model_GuestUser();
        $session = new Zend_Session_Namespace('Default');
        $session->username = $user->getUserName();
        $this->_redirect('index/index');
    }
    
    private function getAuthAdapter() {
    	$authAdapther = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
    	$authAdapther->setTableName('users')
    				 ->setIdentityColumn('username')
    				 ->setCredentialColumn('password')
 					 ->setCredentialTreatment('md5(?)');
		 return $authAdapther;		 
    }


}





